<?php
/**
 * 系统初始化类
 * 
 * @file App.class.php
 * @create 2012-08-02
 * @version v1.0
 * @author veapon 
 * @copyright (C) veapon.com
 */
if( !defined('__ROOT__') ) die('Access Denied');
class App{

	/**
	 * 系统执行
	 * 
	 * @return 
	 * @since v1.0
	 * @create 2012-08-03
	 */
	public static function run(){
		self::init();
		Controller::load( MODULE.'.'.CONTROLLER )->run( ACTION );	
	}

	/**
	 * 系统初始化
	 * 
	 * @return 
	 * @since v1.0
	 * @create 2012-08-03
	 */
	private static function init(){
		// 加载默认配置文件
		global $CONFIGS;
		$sysConf = include_once( __LIB__.'config/default.php' );
		$cusConf = include_once( __APP__.'config/config.php' );
		$CONFIGS = array_merge( $sysConf, $cusConf );

		// 加载核心
		$corePath = __LIB__.'core/';
		if( !is_dir($corePath) ) die("Core path $corePath not found");
		include_once( $corePath.'Common.func.php' );
		include_once( $corePath.'Core.class.php' );
		$h = opendir($corePath);
		while( ($file=readdir($h)) !== false ){
			if( preg_match("/^\w+\.class\.php$/",$file) ){
				include_once($corePath.$file);
			}
		}	
		// 加载模型
		include_once(__LIB__.'database/DB.class.php');
		include_once(__LIB__.'database/Model.class.php');
		closedir($h);

		// 定义系统常量
		define('__URL__', str_replace($_SERVER['DOCUMENT_ROOT'],'http://'.$_SERVER['HTTP_HOST'],__ROOT__));
		define('__STATIC__', __URL__.'static/');
		define('__PLUGIN__', __URL__.'app/plugin/');
		define('__MODEL__', __APP__.'model/');
		define('__CONTROLLER__', __APP__.'controller/');

		$view = C('template_path') ? C('template_path') : __APP__.'view/';
		define('__VIEW__', $view);

		// URL解释
		Router::init();
	}

	/**
	 * 生成核心缓存函数，待完成
	 * 
	 * @return 
	 * @since v1.0
	 * @create 2012-08-06
	 * @todo: 获取PHP文件内容，并替换注释
	 */
	public static function build_runtime(){
		$corePath = __LIB__.'core/';
		if( !is_dir($corePath) ) return false;
		$h = opendir($corePath);
		$ct = '<?php ';
		$reg = "/\/\*(\s|.)*\*\//";
		while( ($file=readdir($h)) !== false ){
			if( preg_match("/^\w+\.class\.php$/",$file) ){
				$tmp = file_get_contents($corePath.$file);
				//echo $tmp;
				//$tmp = substr($tmp,5);
				//$ct .= preg_replace($reg, "", $tmp); 
			}
		}
		closedir($h);
		//return $ct;
	}
}
